package com.sunagy.demand.backend.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/4/25
 * time：下午3:13
 */
public class EncryptUtil {
    private static Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    public EncryptUtil() {
    }

    public static String md5(String inputText) {
        return encryptWithAlgorithm(inputText, "md5");
    }

    public static String sha(SortedMap<String, String> signParams) {
        StringBuffer sb = new StringBuffer();
        Set es = signParams.entrySet();
        Iterator it = es.iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            sb.append(k + "=" + v + "&");
        }

        String params = sb.substring(0, sb.lastIndexOf("&"));
        return sha(params);
    }

    public static String sha(String inputText) {
        return encryptWithAlgorithm(inputText, "sha-1");
    }

    private static String encryptWithAlgorithm(String inputText, String algorithmName) {
        if (inputText != null && !"".equals(inputText.trim())) {
            if (algorithmName == null || "".equals(algorithmName.trim())) {
                algorithmName = "md5";
            }

            Object encryptText = null;

            try {
                MessageDigest m = MessageDigest.getInstance(algorithmName);
                m.update(inputText.getBytes("UTF8"));
                byte[] s = m.digest();
                return hex(s);
            } catch (NoSuchAlgorithmException var5) {
                logger.error("No such algorithm:" + algorithmName, var5);
            } catch (UnsupportedEncodingException var6) {
                logger.error("UnsupportedEncoding:" + algorithmName, var6);
            }

            return (String)encryptText;
        } else {
            throw new IllegalArgumentException("请输入要加密的内容");
        }
    }

    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < arr.length; ++i) {
            sb.append(Integer.toHexString(arr[i] & 255 | 256).substring(1, 3));
        }

        return sb.toString();
    }

    public static byte[] decryptBASE64(String key) {
        try {
            return Base64.decode(key.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var2) {
            throw new RuntimeException(var2);
        }
    }

    public static byte[] encryptBASE64(String key) {
        try {
            return Base64.encode(key.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var2) {
            throw new RuntimeException(var2);
        }
    }

    public static byte[] DESEncrypt(byte[] src, byte[] key) {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key);
            DESKeySpec dks = new DESKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretkey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(1, secretkey, random);
            return cipher.doFinal(src);
        } catch (Exception var7) {
            throw new RuntimeException(var7);
        }
    }

    public static byte[] DESDecrypt(byte[] src, byte[] key) {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key);
            DESKeySpec dks = new DESKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretkey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(2, secretkey, random);
            return cipher.doFinal(src);
        } catch (Exception var7) {
            throw new RuntimeException(var7);
        }
    }

    public static String DESDecrypt(String data, String key) {
        try {
            return new String(DESDecrypt(hex2byte(data.getBytes("UTF-8")), encryptBASE64(key)), "UTF-8");
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException(var3);
        }
    }

    public static String DESEncrypt(String data, String key) {
        if (data != null) {
            try {
                return byte2hex(DESEncrypt(data.getBytes("UTF-8"), encryptBASE64(key)));
            } catch (Exception var3) {
                throw new RuntimeException(var3);
            }
        } else {
            return null;
        }
    }

    public static byte[] AESEncrypt(byte[] src, byte[] key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key);
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(1, secretKeySpec);
            return cipher.doFinal(src);
        } catch (Exception var8) {
            throw new RuntimeException(var8);
        }
    }

    public static byte[] AESDecrypt(byte[] src, byte[] key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key);
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, secretKeySpec);
            return cipher.doFinal(src);
        } catch (Exception var8) {
            throw new RuntimeException(var8);
        }
    }

    public static String AESDecrypt(String data, String key) {
        try {
            return new String(AESDecrypt(hex2byte(data.getBytes("UTF-8")), encryptBASE64(key)), "UTF-8");
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException(var3);
        }
    }

    public static String AESEncrypt(String data, String key) {
        if (data != null) {
            try {
                return byte2hex(AESEncrypt(data.getBytes("UTF-8"), encryptBASE64(key)));
            } catch (Exception var3) {
                throw new RuntimeException(var3);
            }
        } else {
            return null;
        }
    }

    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();

        for(int n = 0; b != null && n < b.length; ++n) {
            String stmp = Integer.toHexString(b[n] & 255);
            if (stmp.length() == 1) {
                hs.append('0');
            }

            hs.append(stmp);
        }

        return hs.toString().toUpperCase();
    }

    private static byte[] hex2byte(byte[] b) throws UnsupportedEncodingException {
        if (b.length % 2 != 0) {
            throw new IllegalArgumentException();
        } else {
            byte[] b2 = new byte[b.length / 2];

            for(int n = 0; n < b.length; n += 2) {
                String item = new String(b, n, 2, "UTF-8");
                b2[n / 2] = (byte)Integer.parseInt(item, 16);
            }

            return b2;
        }
    }
}

